import SuperLocalStorage from 'super-localstorage';

/**
 * 全局尺寸
 */
export class GlobalSizeStorage {
  private readonly key = 'GLOBAL_SIZE';

  private readonly storage: SuperLocalStorage = new SuperLocalStorage();

  public get(): $GlobalSize {
    const size = this.storage.get(this.key);
    if (typeof size === 'string') {
      if (size === 'large' || size === 'default' || size === 'small') {
        return size;
      }
    }
    return 'default';
  }

  public set(size: $GlobalSize) {
    this.storage.set(this.key, size);
  }
}

/**
 * layout侧边栏的折叠(收起)状态
 */
export class SidebarCollapseStorage {
  private readonly key: string = 'SIDEBAR_COLLAPSE_STATUS';

  private readonly storage: SuperLocalStorage = new SuperLocalStorage();

  // true——代表收起; false——代表不收起; null——代表没有储存过
  public get() {
    const status = this.storage.get(this.key);
    return typeof status === 'boolean' ? status : null;
  }

  // true——代表收起; false——代表不收起
  public set(status: boolean | null) {
    this.storage.set(this.key, typeof status === 'boolean' ? status : -1);
  }
}

/**
 * 是否安装了PWA应用 (手动卸载无法准确感知)
 */
export class IsInstallPwaStorage {
  private readonly key = 'IS_INSTALL_PWA';

  private readonly storage: SuperLocalStorage = new SuperLocalStorage();

  public get() {
    const isPwa = ['fullscreen', 'standalone', 'minimal-ui'].some((displayMode) => window.matchMedia(`(display-mode: ${displayMode})`).matches);
    if (isPwa) {
      this.set(true);
      return true;
    } else {
      const isInstall = this.storage.get(this.key) ?? null;
      return isInstall === null ? null : Boolean(isInstall);
    }
  }

  public set(isInstall: boolean) {
    this.storage.set(this.key, isInstall, new Date().getTime() + 1000 * 60 * 60 * 24 * 10); // 十天有效期
  }
}
